// 二次封装axios
import router from "@/router";
import { settingConfigStore } from "@/stores";
import axios from "axios";
import { Toast, showLoadingToast, closeToast, showToast } from "vant";
//  axios的配置
const baseURL = "/api";
const request = axios.create({
  baseURL,
  timeout: 5000,
});
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 修改请求头
    const store = settingConfigStore();

    console.log(store.configInfo);

    // if (store.configInfo.token && config.headers) {
    // config.headers.Authorization =
    //   "Bearer eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6ImZmYWI4YWE4LWE1Y2ItNGE0Yy05ZTk1LWYwYTYzYjYzYjdhZCJ9.JtFo8ZwPkRZeU0WnKAkagR5e2cH2eoOk1tsJ4_edWEwspnXqMA7I8fC1QglAPSG8Gb9ocvtO4YF-YgTzr2EG2Q"
    config.headers.Authorization = `Bearer ${store.configInfo.token}`;
    // }
    showLoadingToast({
      message: "加载中...",
      forbidClick: true,
      duration: 0,
    });
    return config;
  },
  (err) => Promise.reject(err)
);
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    // status 是200是响应成功
    if (res.data.code == 401) {
      closeToast();
      showToast("登录过期，请重新登录");
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/auth/login",
        });
      }, 1000);
      return Promise.reject(res.data);
    }
    closeToast();
    return res.data;
  },
  (err) => {
    // 请求报错，响应出错
    // if (err.response.status === 401) {
    //   router.push(`/login`);
    // }
    closeToast();
    return Promise.reject(err);
  }
);

export default request;
